package com.github.im.module;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.im.QcloudImProperties;
import com.github.im.constants.QcloudImConstants;
import com.github.im.constants.TlsSig;
import com.github.im.module.sig.TlsSigStrategy;
import com.github.im.module.sig.UserSig;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public abstract class AbstractHttpClient {

    private Long sdkAppId;
    private String privateKey;
    private String adminIdentifier;
    private TlsSig tlsSig;
    private Long expire;
    private ObjectMapper objectMapper;

    protected AbstractHttpClient(QcloudImProperties qcloudImProperties) {
        this.sdkAppId = qcloudImProperties.getSdkAppId();
        this.privateKey=qcloudImProperties.getPrivateKeyPath();
        this.adminIdentifier = qcloudImProperties.getAdminIdentifier();
        this.tlsSig = qcloudImProperties.getTlsSig();
        this.expire = qcloudImProperties.getExpire();
        this.objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
    protected String buildUrl(String api) {
        return QcloudImConstants.DOMAIN + api +
                "?sdkappid=" + sdkAppId +
                "&identifier=" + adminIdentifier +
                "&usersig=" + generateUserSig(adminIdentifier) +
                "&random=" + random() +
                "&contenttype=" + contentType();
    }

    protected String postParamsJson(String url, AbstractRequest abstractRequest) {
        try {
            // 构建请求数据
            String requestJson = objectMapper.writeValueAsString(abstractRequest);
            if (log.isDebugEnabled()) {
                log.debug("【腾讯云】>>>【即时通信】>>>请求地址：{}>>>请求数据：{}", url, requestJson);
            }
            log.info("请求地址:{}",url);
            String body = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                    .body(requestJson)
                    .execute().body();
            // 获取响应数据
            return body;
        } catch (JsonProcessingException e) {
            String msg = "【腾讯云】>>>【即时通信】>>>数据转换异常";
            log.error(msg, e);
            throw new RuntimeException(msg);
        }
    }
    protected <T extends AbstractResponse> T convert(String json, Class<T> targetClass) {
        try {
            return objectMapper.readValue(json, targetClass);
        } catch (JsonProcessingException e) {
            String msg = "【腾讯云】>>>【即时通信】>>>数据转换异常";
            log.error(msg, e);
            throw new RuntimeException(msg);
        }
    }

    protected String generateUserSig(String identifier) {
        try {
            TlsSigStrategy tlsSigStrategy = tlsSig.getStrategy().newInstance();
            UserSig userSig = new UserSig(tlsSigStrategy);
            return userSig.generate(sdkAppId, privateKey, expire, identifier);
        } catch (Exception e) {
            String msg = "【腾讯云】>>>【即时通信】>>>签名生成异常";
            log.error(msg, e);
            throw new RuntimeException(msg);
        }
    }

    private long random() {
        Random random = new Random(System.currentTimeMillis() / 1000);
        return random.nextInt(900000) + 100000;
    }

    private String contentType() {
        return "json";
    }


}
